package com.rchat.pocmini.activity.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.aso.common.dialog.AlertDialogCustomConfirm;
import com.aso.common.http.utils.HttpUtils;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.adapter.FriendListViewAdapter;
import com.rchat.pocmini.activity.addfriend.AddFriendMvpActivity;
import com.rchat.pocmini.activity.bean.FriendBean;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.RequestParam;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.util.HttpUtil;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ljd on 2017/3/10.
 */

public class FriendFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemLongClickListener {

    private static final int HANDLETYPE_UPDATE_FRIENDS = 1;
    private static final int HANDLETYPE_QUERY_FRIENDS = 2;

    private ListView lvFriend;
    private ImageView ivAddFriend;
    private ArrayList<FriendBean> friendList = new ArrayList<>();
    private FriendListViewAdapter adapter;
    private View view;
    private ProgressBar pb;
    public static FriendFragment instance;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            pb.setVisibility(View.GONE);
            switch (msg.what) {
                case HANDLETYPE_UPDATE_FRIENDS:
                    String backJson = (String) msg.obj;
                    try {
                        JSONObject json = new JSONObject(backJson);
                        if (json.getString("code").equals("200")) {
                            JSONObject data = json.getJSONObject("data");
                            JSONObject users = data.getJSONObject("users");
                            JSONArray userArray = users.getJSONArray("user");
                            friendList.clear();
                            for (int i = 0; i < userArray.length(); i++) {
                                JSONObject j = userArray.getJSONObject(i);
                                FriendBean bean = new FriendBean();
                                bean.setName(j.getString("display"));
                                bean.setId(j.getString("account"));
                                bean.setUserName(j.getString("userName"));
                                friendList.add(bean);
                            }
                            adapter.notifyDataSetChanged();
                        } else if (json.getString("code").equals("406")){
                            /**
                             * 2017.07.13
                             * 苏登福
                             * bug：【睿洽对讲安卓公众版】无法成功删除最后一个好友
                             * 原因：没有好友时，服务器返回406：该账号还未添加好友 没有做列表处理
                             */
                            friendList.clear();
                            adapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case HANDLETYPE_QUERY_FRIENDS:
                    queryFriend();
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.friend_list_fragment, container, false);
        initView(view);
        instance = this;
        return view;
    }

    private void initView(View view) {
        pb = (ProgressBar) view.findViewById(R.id.pb);
        lvFriend = (ListView) view.findViewById(R.id.list_view_friend);
        ivAddFriend = (ImageView) view.findViewById(R.id.iv_add_friend);
        ivAddFriend.setOnClickListener(this);
        adapter = new FriendListViewAdapter(getContext(), friendList);
        lvFriend.setAdapter(adapter);
        lvFriend.setEmptyView(view.findViewById(R.id.tv_empty));
        lvFriend.setOnItemLongClickListener(this);
//        View emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.friend_list_view_empty,null);
//        ((ViewGroup)lvFriend.getParent()).addView(emptyView);
//        lvFriend.setEmptyView(emptyView);
        queryFriend();
    }

    public void queryFriend() {
        String questJson = queryFriendJson(AirtalkeeAccount.getInstance().getUserId());
        startQueryFriendThread(questJson);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_add_friend:
                Intent intent = new Intent();
//                intent.setClass(getApplication(), AddFriendActivity.class);
                intent.setClass(getContext(), AddFriendMvpActivity.class);
                startActivity(intent);
                break;
        }
    }


    /**
     * 生成创建群组的请求json
     *
     * @param userName 创建者
     * @return json
     */
    private String queryFriendJson(String userName) {
        Map<String, String> param = new HashMap<>();
        param.put("userName", userName);
        //body = {"code":1034,"data":{"platform":1,"version":"1.0","enterprise":1,"userName":"111110000118"}}
        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1034, param);

        return body;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("FriendFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("FriendFragment");
    }

    /**
     * 执行创建群组线程
     *
     * @param requestJson 创建群组请求json
     */
    private void startQueryFriendThread(final String requestJson) {
        pb.setVisibility(View.VISIBLE);
        Thread thread = new Thread() {
            @Override
            public void run() {
                String backJson = HttpUtil.httpConnect(UrlsGlobal.getUrl(UrlsGlobal.QUERY_FRIEND_LIST), requestJson, HttpUtil.HTTP_POST);
                Message message = new Message();
                message.what = HANDLETYPE_UPDATE_FRIENDS;
                message.obj = backJson;
//                    createGroupResultHandler.sendMessage(message);
                handler.sendMessage(message);
            }
        };
        thread.start();
    }

    /**
     * 执行创建群组线程
     *
     * @param requestJson 创建群组请求json
     */
    private void startDelFriendThread(final String requestJson) {
        pb.setVisibility(View.VISIBLE);
        Thread thread = new Thread() {
            @Override
            public void run() {
                String backJson = HttpUtil.httpConnect(UrlsGlobal.getUrl(UrlsGlobal.DEL_FRIEND), requestJson, HttpUtil.HTTP_POST);
                Message message = handler.obtainMessage();
                message.what = 2;
                message.obj = backJson;
//                    createGroupResultHandler.sendMessage(message);
                handler.sendMessage(message);
            }
        };
        thread.start();
    }

    public void delFriend(final FriendBean bean) {
        AlertDialogCustomConfirm.Builder builder = new AlertDialogCustomConfirm.Builder(getContext());
        builder.setTitle(getString(R.string.tip_confirm_delete_friend))
                .setPositiveButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击“确认”后的操作

                        Map<String, String> param = new HashMap<>();
                        param.put("userName", AirtalkeeAccount.getInstance().getUserId());
                        param.put("otherName", bean.getUserName());
                        //body = {"code":1037,"data":{"platform":1,"version":"1.0","enterprise":1,"otherName":"111110000088","userName":"111110000118"}}
                        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1037, param);
                        startDelFriendThread(body);
                    }
                })
                .setNegativeButton(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create().show();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        delFriend((FriendBean) adapter.getItem(position));
        return true;
    }
}
